package com.pony.iphone.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pony.iphone.dto.AnswerRecord;
import com.pony.iphone.dto.HistoryStats;
import com.pony.iphone.dto.QuestionAnswerDto;
import com.pony.iphone.dto.QuestionRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class QWenHistoryService {
    
    private static final String HISTORY_DIR = "./qwen_history";
    private static final String QUESTIONS_FILE = "questions.json";
    private static final String ANSWERS_FILE = "answers.json";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final Set<String> questionCache = ConcurrentHashMap.newKeySet();
    
    /**
     * 初始化历史记录目录
     */
    public void initHistoryDirectory() {
        try {
            Path historyPath = Paths.get(HISTORY_DIR);
            if (!Files.exists(historyPath)) {
                Files.createDirectories(historyPath);
                log.info("创建问答历史目录: {}", historyPath.toAbsolutePath());
            }
            
            // 初始化问题文件
            Path questionsPath = Paths.get(HISTORY_DIR, QUESTIONS_FILE);
            if (!Files.exists(questionsPath)) {
                Files.createFile(questionsPath);
                // 写入空数组
                Files.write(questionsPath, "[]".getBytes(StandardCharsets.UTF_8));
            }
            
            // 初始化答案文件
            Path answersPath = Paths.get(HISTORY_DIR, ANSWERS_FILE);
            if (!Files.exists(answersPath)) {
                Files.createFile(answersPath);
                Files.write(answersPath, "[]".getBytes(StandardCharsets.UTF_8));
            }
            
            // 加载现有问题到缓存
            loadQuestionsToCache();
            
        } catch (Exception e) {
            log.error("初始化问答历史目录失败", e);
        }
    }
    
    /**
     * 记录问答历史
     */
    public void recordQAHistory(QuestionAnswerDto questionDto, String aiAnswer, String finalAnswer) {
        try {
            String questionKey = generateQuestionKey(questionDto);
            
            // 检查是否重复问题
            if (questionCache.contains(questionKey)) {
                log.debug("问题已存在，跳过记录: {}", questionDto.getQuestion());
                return;
            }
            
            // 添加到缓存
            questionCache.add(questionKey);
            
            // 记录问题
            recordQuestion(questionDto);
            
            // 记录答案
            recordAnswer(questionDto, aiAnswer, finalAnswer);
            
            log.info("记录问答历史 - 问题: {}, AI回答: {}, 最终答案: {}", 
                    questionDto.getQuestion(), aiAnswer, finalAnswer);
                    
        } catch (Exception e) {
            log.error("记录问答历史失败", e);
        }
    }
    
    /**
     * 记录问题
     */
    private void recordQuestion(QuestionAnswerDto questionDto) {
        try {
            Path questionsPath = Paths.get(HISTORY_DIR, QUESTIONS_FILE);
            List<QuestionRecord> questionRecords = loadQuestionsFromFile();
            
            QuestionRecord record = QuestionRecord.builder()
                .question(questionDto.getQuestion())
                .answerList(new ArrayList<>(questionDto.getAnswerList()))
                .libraryName(questionDto.getLibraryName())
                .createTime(LocalDateTime.now().format(DATE_FORMATTER))
                .questionKey(generateQuestionKey(questionDto))
                .build();
            
            questionRecords.add(record);
            
            // 写入文件
            String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(questionRecords);
            Files.write(questionsPath, json.getBytes(StandardCharsets.UTF_8));
            
        } catch (Exception e) {
            log.error("记录问题失败", e);
        }
    }
    
    /**
     * 记录答案
     */
    private void recordAnswer(QuestionAnswerDto questionDto, String aiAnswer, String finalAnswer) {
        try {
            Path answersPath = Paths.get(HISTORY_DIR, ANSWERS_FILE);
            List<AnswerRecord> answerRecords = loadAnswersFromFile();
            
            AnswerRecord record = AnswerRecord.builder()
                .question(questionDto.getQuestion())
                .questionKey(generateQuestionKey(questionDto))
                .aiAnswer(aiAnswer)
                .finalAnswer(finalAnswer)
                .answerList(new ArrayList<>(questionDto.getAnswerList()))
                .answerTime(LocalDateTime.now().format(DATE_FORMATTER))
                .build();
            
            answerRecords.add(record);
            
            // 写入文件
            String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(answerRecords);
            Files.write(answersPath, json.getBytes(StandardCharsets.UTF_8));
            
        } catch (Exception e) {
            log.error("记录答案失败", e);
        }
    }
    
    /**
     * 生成问题唯一键（用于去重）
     */
    private String generateQuestionKey(QuestionAnswerDto questionDto) {
        String question = questionDto.getQuestion().toLowerCase().trim();
        List<String> sortedAnswers = new ArrayList<>(questionDto.getAnswerList());
        Collections.sort(sortedAnswers);
        
        return question + "|" + String.join(",", sortedAnswers);
    }
    
    /**
     * 从文件加载问题到缓存
     */
    private void loadQuestionsToCache() {
        try {
            List<QuestionRecord> records = loadQuestionsFromFile();
            for (QuestionRecord record : records) {
                questionCache.add(record.getQuestionKey());
            }
            log.info("加载 {} 个历史问题到缓存", records.size());
        } catch (Exception e) {
            log.error("加载问题缓存失败", e);
        }
    }
    
    /**
     * 从文件加载问题记录
     */
    private List<QuestionRecord> loadQuestionsFromFile() {
        try {
            Path questionsPath = Paths.get(HISTORY_DIR, QUESTIONS_FILE);
            if (!Files.exists(questionsPath)) {
                return new ArrayList<>();
            }
            
            String content = new String(Files.readAllBytes(questionsPath), StandardCharsets.UTF_8);
            return objectMapper.readValue(content, 
                objectMapper.getTypeFactory().constructCollectionType(List.class, QuestionRecord.class));
        } catch (Exception e) {
            log.error("加载问题文件失败", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 从文件加载答案记录
     */
    private List<AnswerRecord> loadAnswersFromFile() {
        try {
            Path answersPath = Paths.get(HISTORY_DIR, ANSWERS_FILE);
            if (!Files.exists(answersPath)) {
                return new ArrayList<>();
            }
            
            String content = new String(Files.readAllBytes(answersPath), StandardCharsets.UTF_8);
            return objectMapper.readValue(content, 
                objectMapper.getTypeFactory().constructCollectionType(List.class, AnswerRecord.class));
        } catch (Exception e) {
            log.error("加载答案文件失败", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取历史统计
     */
    public HistoryStats getHistoryStats() {
        try {
            List<QuestionRecord> questions = loadQuestionsFromFile();
            List<AnswerRecord> answers = loadAnswersFromFile();
            
            return HistoryStats.builder()
                .totalQuestions(questions.size())
                .totalAnswers(answers.size())
                .uniqueQuestions(questionCache.size())
                .lastUpdateTime(LocalDateTime.now().format(DATE_FORMATTER))
                .build();
        } catch (Exception e) {
            log.error("获取历史统计失败", e);
            return HistoryStats.builder().build();
        }
    }
    
    /**
     * 导出历史数据
     */
    public File exportHistory() throws IOException {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String exportFileName = String.format("qwen_history_%s.json", timestamp);
        Path exportPath = Paths.get(HISTORY_DIR, exportFileName);
        
        Map<String, Object> exportData = new HashMap<>();
        exportData.put("exportTime", LocalDateTime.now().format(DATE_FORMATTER));
        exportData.put("questions", loadQuestionsFromFile());
        exportData.put("answers", loadAnswersFromFile());
        exportData.put("statistics", getHistoryStats());
        
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(exportData);
        Files.write(exportPath, json.getBytes(StandardCharsets.UTF_8));
        
        return exportPath.toFile();
    }
}